package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.text.StrSpliter;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.BlackListMapper;
import com.tanhua.common.mapper.QuestionMapper;
import com.tanhua.common.mapper.SettingsMapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.*;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.dubbo.server.api.RecommedApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLikeListVo;
import com.tanhua.server.vo.BlackListVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.SettingsVo;
import com.tanhua.server.vo.UserInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MyCenterService {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;
    @Reference(version = "1.0.0")
    private RecommedApi recommedApi;
    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;
    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;
    @Autowired
    private BlacklistService blacklistService;

    @Autowired
    private IMService imService;
    @Autowired
    private TanHuaService tanHuaService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private BlackListMapper blackListMapper;
    @Autowired
    private SettingsMapper settingsMapper;


    /**
     * 通过用户id查询用户的信息
     *
     * @param userId
     * @return
     */
    public UserInfoVo queryUserInfoByUserId(Long userId) {
        if (ObjectUtil.isEmpty(userId)) {
            //如果查询id为null，就表示查询当前用户信息
            userId = UserThreadLocal.get().getId();
        }

        //查询用户信息
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(userId);
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }

        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
        //userInfoVo.setGender(userInfo.getSex().toString().toLowerCase());
        userInfoVo.setGender(userInfo.getSex().getValue() == 1 ? "man" : "women");
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        return userInfoVo;
    }

    /**
     * 实现功能:查询互相关注、我关注、粉丝、谁看过我 - 翻页列表
     *
     * @param page
     * @param pageSize
     * @param nickname
     * @param type
     * @return
     */
    public PageResult getAllLikeList(Integer page, Integer pageSize, String nickname, Integer type) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        List<Object> list;
        switch (type) {
            case 1:
                list = CollUtil.getFieldValues(userLikeApi.queryMutualLikeList(userId, page, pageSize).getRecords(), "userId");
                break;
            case 2:
                list = CollUtil.getFieldValues(userLikeApi.queryLikeList(userId, page, pageSize).getRecords(), "userId");
                break;
            case 3:
                list = CollUtil.getFieldValues(userLikeApi.queryFanList(userId, page, pageSize).getRecords(), "userId");
                break;
            case 4:
                list = CollUtil.getFieldValues(visitorsApi.queryMyVisitorAll(userId, page, pageSize), "visitorUserId");
                break;
            default:
                return pageResult;
        }
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.in("user_id", list);
        if (StrUtil.isNotEmpty(nickname)) {
            wrapper.like("nick_name", nickname);
        }
        List<UserInfo> userInfos = userInfoMapper.selectList(wrapper);
        List<UserLikeListVo> likeListVos = new ArrayList<>();
        //封装用户信息
        for (UserInfo userInfo : userInfos) {
            UserLikeListVo vo = new UserLikeListVo();
            vo.setAge(userInfo.getAge());
            vo.setAvatar(userInfo.getLogo());
            vo.setCity(StrSpliter.split(userInfo.getCity(), '-', 0, true, true).get(0));
            vo.setEducation(userInfo.getEdu());
            vo.setGender(userInfo.getSex().name().toLowerCase());
            vo.setId(userInfo.getUserId());
            vo.setNickname(userInfo.getNickName());
            vo.setMarriage(StringUtils.equals(userInfo.getMarriage(), "已婚") ? 1 : 0);
            vo.setMatchRate(Convert.toInt(recommedApi.getFatcvalue(userId, userInfo.getUserId())));
            vo.setAlreadyLove(userLikeApi.isLike(userId, userInfo.getUserId()));
            likeListVos.add(vo);
        }
        pageResult.setItems(likeListVos);
        return pageResult;
    }


    /**
     * 更新用户信息
     *
     * @param userInfoVo
     * @return
     */
    public Boolean updateUserInfo(UserInfoVo userInfoVo) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        UserInfo userInfo = new UserInfo();
        //设置用户信息
        userInfo.setUserId(userId);
        userInfo.setCity(userInfoVo.getCity());
        userInfo.setSex(userInfoVo.getGender() == "man" ? SexEnum.MAN : SexEnum.WOMAN);
        //userInfo.setAge(Convert.toInt(userInfoVo.getAge()));
        userInfo.setBirthday(userInfoVo.getBirthday());
        userInfo.setNickName(userInfoVo.getNickname());
        userInfo.setEdu(userInfoVo.getEducation());
        userInfo.setIndustry(userInfoVo.getProfession());
        userInfo.setIncome(StringUtils.replaceAll(userInfoVo.getIncome(), "K", ""));
        userInfo.setMarriage(userInfoVo.getMarriage() == 1 ? "已婚" : "未婚");
        //修改用户信息
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        int update = userInfoMapper.update(userInfo, wrapper);
        return update > 0;
    }

    /**
     * 取消喜欢
     *
     * @param userId
     */
    public void disLike(Long userId) {
        User user = UserThreadLocal.get();
        Long id = user.getId();
        //1.判断是否相互喜欢
        boolean result = userLikeApi.isMutualLike(userId, id);
        //2.删除喜欢的关系
        Boolean aBoolean = userLikeApi.notLikeUser(id, userId);
        //3.删除环信用户关系
        if (result) {
            imService.deleteContactUser(userId);
        }
    }

    /**
     * 喜欢
     *
     * @param userId
     */
    public void likeFan(Long userId) {
        //喜欢用户，如果用户是相互喜欢的话就会成为好友
        this.tanHuaService.likeUser(userId);
    }


    /**
     * 查询通用设置
     *
     * @return
     */
    public SettingsVo querySettings() {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        String mobile = user.getMobile();
        SettingsVo settingsVo = new SettingsVo();
        settingsVo.setId(userId);
        settingsVo.setPhone(mobile);
        settingsVo.setStrangerQuestion(questionService.getQuestion(Convert.toInt(userId)));
        Settings settings = imService.findSettings(userId);
        if (ObjectUtil.isNotEmpty(settings)) {
            settingsVo.setGonggaoNotification(settings.getGonggaoNotification());
            settingsVo.setLikeNotification(settings.getLikeNotification());
            settingsVo.setPinglunNotification(settings.getPinglunNotification());
        }
        return settingsVo;
    }


    /**
     * 保存陌生人问题
     *
     * @param content
     */
    public void saveQuestions(String content) {
        //1.获取陌生人问题
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        QueryWrapper<Question> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        Question question = questionMapper.selectOne(wrapper);
        //2.判断陌生人问题是否为空
        if (ObjectUtil.isEmpty(question)) {
            //3.新增陌生人问题
            question = new Question();
            question.setTxt(content);
            question.setUserId(userId);
            question.setCreated(new Date());
            question.setUpdated(question.getCreated());
            questionMapper.insert(question);
        } else {
            //更新陌生人问题
            question.setTxt(content);
            questionMapper.update(question, wrapper);
        }


    }

    /**
     * 查询黑名单
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryBlacklist(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        List<BlackListVo> listVos = new ArrayList<>();
        IPage<BlackList> pageList = blacklistService.queryBlacklist(userId, page, pageSize);
        for (BlackList blackList : pageList.getRecords()) {
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", blackList.getBlackUserId());
            UserInfo userInfo = userInfoMapper.selectOne(wrapper);
            BlackListVo blackListVo = new BlackListVo();
            blackListVo.setAge(userInfo.getAge());
            blackListVo.setAvatar(userInfo.getLogo());
            blackListVo.setGender(userInfo.getSex().toString().toLowerCase());
            blackListVo.setNickname(userInfo.getNickName());
            blackListVo.setId(blackList.getBlackUserId());
            listVos.add(blackListVo);
        }

        pageResult.setItems(listVos);
        return pageResult;
    }


    /**
     * 根据用户id删除,黑名单中的用户记录
     *
     * @param userHeiId
     */
    public void delBlacklist(Long userHeiId) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        QueryWrapper<BlackList> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("black_user_id", userHeiId);
        blackListMapper.delete(wrapper);
    }


    /**
     * 业务层实现功能:设置更新通知
     *
     * @param likeNotification
     * @param pinglunNotification
     * @param gonggaoNotification
     */
    public void setNotificationsSetting(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        QueryWrapper<Settings> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        Settings settings = settingsMapper.selectOne(wrapper);
        if (ObjectUtil.isEmpty(settings)) {
            //新增
            settings = new Settings();
            settings.setGonggaoNotification(gonggaoNotification);
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setUserId(userId);
            settingsMapper.insert(settings);
        } else {
            //更新
            settings.setPinglunNotification(pinglunNotification);
            settings.setLikeNotification(likeNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsMapper.update(settings, wrapper);
        }
    }
}